package com.basejace.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.basejace.common.model.PubDictgroup;
import com.basejace.common.model.PubRole;
import com.basejace.common.model.PubUser;
import com.basejace.common.model.PubUserdepartmentRela;
import com.basejace.common.utils.MD5;
import com.basejace.core.R;
import com.basejace.core.base.BaseController;
import com.basejace.core.model.PageBootstrapTable;
import com.basejace.core.sequence.Sequence;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class UserController extends BaseController {
	
	public UserController() {
		setModelClass(PubUser.class);
	}
	public void show() {
		setAttr("dptid", getPara("dptid"));
		render("list.jsp");
	}
	
	public void list() {
		String username = getPara("username");
		String mobileno = getPara("mobileno");
		String sex = getPara("sex");
		Long dptid = getParaToLong("dptid");
		
		
		
		
		
		String sqlExceptSelect = "from pub_user where 1=1 ";
		List sqlCondition = new ArrayList();
		if (StrKit.notBlank(username)) {
			sqlExceptSelect += "and username like ? ";
			sqlCondition.add("%" + username + "%");
		}
		if (StrKit.notBlank(mobileno)) {
			sqlExceptSelect += "and mobileno like ? ";
			sqlCondition.add("%" + mobileno + "%");
		}
		if (StrKit.notBlank(sex)) {
			sqlExceptSelect += "and sex = ? ";
			sqlCondition.add(sex);
		}
		String userids = null;
		/*if (dptid != null) {
			try {
				List<PubUserdepartmentRela> list = PubUserdepartmentRela.dao.find("select * from pub_userdepartment_rela where departmentid=?", dptid);
				List<Long> useridList = new ArrayList<Long>();
				
				for (Iterator<PubUserdepartmentRela> iterator = list.iterator(); iterator.hasNext();) {
					PubUserdepartmentRela userdeparmentRela = iterator.next();
					useridList.add(userdeparmentRela.getUserid());
				}
				if (useridList != null && useridList.size()>0) {
					userids = Arrays.toString(useridList.toArray());
					userids = StringUtils.replacePattern(userids, "\\[|\\]", "");
					log.info("部门用户列表：" + userids);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				
				return;
			}
			if (StringUtils.isNotBlank(userids)) {
				sqlExceptSelect += "and userid in (?) ";
				sqlCondition.add(userids);
			}
		}*/

		int offset = getParaToInt("offset");
		int limit = getParaToInt("limit");
		int pageNumber = (offset) / limit + 1;
		
		Page<Record> page = Db.paginate(pageNumber, limit, "select * ", sqlExceptSelect , sqlCondition.toArray());
		
		List<Record> list = page.getList();
		List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Record object = (Record) iterator.next();
			rows.add(object.getColumns());
		}
		
		PageBootstrapTable p = new PageBootstrapTable();
		p.setTotal(page.getTotalRow());
		p.setPageSize(page.getPageSize());
		p.setPageNumber(page.getPageNumber());
		p.setRows(rows);
		
		renderJson(p);
	}
	public void beforeAdd() {
		this.setAttr("message", "新建员工信息");
	}
	
	
	/*public void view() {
		PubUser user = PubUser.dao.findById(getParaToLong("PK"));
		setAttr(getModelSimpleName(), user);
		
		
		
		this.setAttr(R.Key.IS_EDIT, R.Const.FALSE);
		this.setAttr(R.Key.IS_NEW, R.Const.FALSE);
		render("content.jsp");
	}*/
	
	public void beforeView() throws Exception {
		//获取用户所属角色发送到页面
		List<Long> roleidList = Db.query("select roleid from pub_userrole_rela where userid=?", getModelEntity().get("userid"));
		if (roleidList != null && roleidList.size() > 0) {
			String roles = StringUtils.replacePattern(Arrays.toString(roleidList.toArray()), "[\\[\\]\\s]", "");
			if (StringUtils.isNotBlank(roles)) {
				this.setAttr("roleids", roles);
			}
		}
		
		//获取所属组织架构到页面
		List<Long> dptidList = Db.query("select departmentid from pub_userdepartment_rela where userid=?", getModelEntity().get("userid"));
		if (dptidList != null && dptidList.size() > 0) {
			String dptids = StringUtils.replacePattern(Arrays.toString(dptidList.toArray()), "[\\[\\]\\s]", "");
			if (StringUtils.isNotBlank(dptids)) {
				this.setAttr("dptids", dptids);
			}
		}
	}
	public void beforeSave() throws Exception {
		getModelEntity().set("userid", Sequence.getSequence())
			.set("password", MD5.encode(R.Const.DEFAULT_UESR_PWD));
	}
	@Before(Tx.class)
	public void save() {
		String isNew = this.getPara(R.Key.IS_NEW);
		this.modelEntity = getModel(getModelClass(), getModelSimpleName(), true); //忽略转换错误
		
		try {
			if (R.Const.TRUE.equals(isNew)) {
				//这里是新建
				this.beforeSave();
				modelEntity.save();
				this.afterSave();
				this.setAttr(MSG, "新增成功");
			} else {
				//这里是更新
				this.beforeUpdate();
				modelEntity.update();
				this.afterUpdate();
				this.setAttr(MSG, "修改成功");
			}
			
			//这里是对角色删除重新设置
		} catch (Exception e) {
			e.printStackTrace();
			this.setAttr(MSG, e.getMessage());
		}
		this.setAttr(getModelSimpleName(), this.modelEntity);
		this.setAttr(R.Key.IS_EDIT, R.Const.FALSE);
		this.setAttr(R.Key.IS_NEW, R.Const.FALSE);
		
		render(CONTENT);
		
		PubUser user = getModel(PubUser.class, "user", true);
		Map<String, String[]> params = getParaMap();
		System.out.println(user.toString());
		
		if (user.getUserid() == null) {
			user.setUserid(Sequence.getSequence());
//			user.setPassword();
			user.save();
			this.setAttr("message", "保存成功");
		} else {
			user.update();
			this.setAttr("message", "更新成功");
		}
		
		this.setAttr("user", user);
		render("content.jsp");
	}
	
	@Before(Tx.class)
	public void delete() {
		String referer = getRequest().getHeader("referer");
		log.info("[referer]:" + referer);
		boolean result = false;
		try {
			String pks = getPara("PK");
			if (StrKit.notBlank(pks) && pks.endsWith(",") && pks.length() > 1) {
				pks = pks.substring(0, pks.length()-1);
			}
			log.info("delete pks:" + pks);
			int num = Db.update("delete from pub_user where userid in (" + pks + ")");
			result = true;
			//result = PubUser.dao.deleteById(getParaToLong("PK"));
		} catch (Exception e) {
			PubUser user = PubUser.dao.findById(getParaToLong("PK"));
			setAttr("message", "删除失败！"+e.getMessage());
			setAttr("user", user);
			render("content.jsp");
		}
		
		if (result) {
			setAttr("message", "删除成功！");
			render("list.jsp");
		} else {
			//PubUser user = PubUser.dao.findById(getParaToLong("PK"));
			setAttr("message", "删除失败！请联系管理员");
			//setAttr("user", user);
			render("content.jsp");
		}
	}
}
